﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<link href="~/lib/layui/css/layui.css" rel="stylesheet" />
<script src="~/lib/layui/layui.js"></script>
<script src="~/js/js.cookie.js"></script>
<script src="~/js/moment.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Demo</title>
    <!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
    <link href="//unpkg.com/layui@2.9.20/dist/css/layui.css" rel="stylesheet">
    @* 导出引入文件 *@
    <title>Layui with XLSX</title>
    <!-- 引入Layui的CSS -->
    @* <link rel="stylesheet" href="path/to/layui.css"> *@
    <!-- 引入XLSX库的CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
    <title>Layui 导入按钮示例</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.8/css/layui.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.8/layui.js"></script>
</head>
<body>
    <form class="layui-form" action="">
        <h3 class="bold-large" layui-icon-question>查询条件</h3>
        <div class="layui-form-item">
            <div class="layui-form-item">

                <div class="layui-inline">
                    <label class="layui-form-label">工作中心编码</label>
                    <div class="layui-input-block">
                        <input type="text" id="workCenterCode" placeholder="请输入" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label">工作中心名称</label>
                    <div class="layui-input-block">
                        <input type="text" id="workCenterName" placeholder="请输入" class="layui-input">
                    </div>

                </div>

                <div class="layui-inline">
                    <label class="layui-form-label">工作中心类型</label>
                    <div class="layui-input-block">
                        <select id="workCenterType" lay-filter="testSelect1">
                            <option value="">请选择</option>
                            <option value="加工组">加工组</option>
                            <option value="生产组">生产组</option>
                        </select>
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <select id="workCenterState" lay-filter="testSelect2">
                            <option value="0">请选择</option>
                            <option value="1">有效</option>
                            <option value="2">无效</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="demo-table-search">查询</button>
                        <button type="button" class="layui-btn layui-bg-blue">导出</button>
                        <button type="button" class="layui-btn layui-btn-normal" id="upload-btn">
                            <i class="layui-icon layui-icon-upload"></i> 文件导入
                        </button>
                        <input type="file" id="fileInput" style="display: none;" />
                    </div>
                </div>
                <button type="button" class="layui-btn layui-bg-red" lay-on="test-iframe-curl" onclick="AddWorkCenter()">+新增</button>
            </div>
        </div>
        <h3 class="bold-large" layui-icon-question>工作中心列表</h3>
        <table class="layui-table">
            <thead>
                <tr>
                    <td>序号</td>
                    <td>工作中心编码</td>
                    <td>工作中心名称</td>
                    <td>工作中心类型</td>
                    <td>班次</td>
                    <td>创建人</td>
                    <td>创建时间</td>
                    <td>状态</td>
                    <td>审批状态</td>
                    <td>操作</td>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
        <div id="demo-laypage-all"></div>
    </form>

    <script src="//unpkg.com/layui@2.9.18/dist/layui.js"></script>
    <script>

        layui.use(['form', 'laydate', 'util'], function () {
            var form = layui.form
            var upload = layui.upload;
            var layer = layui.layer;
            var laypage = layui.laypage;
            var $ = layui.$;
            var layer = layui.layer;
            var util = layui.util;
            var pageIndex = 1;
            var pageSize = 10;
            var ProcessStatus = "";
            $(function () {
                ShowWorkCenter(pageIndex, pageSize, 0);
            })


            //导入
            document.getElementById('upload-btn').addEventListener('click', function () {
                document.getElementById('fileInput').click();
            });

            document.getElementById('fileInput').addEventListener('change', function (e) {
                var file = e.target.files[0];
                if (file) {
                    var formData = new FormData();
                    formData.append('file', file);

                    $.ajax({
                        url: '@ViewBag.RedDragonWrite' + "/api/WorkCenter/ImportWorkCenter", // 确保这部分在服务器端已经正确渲染
                        data: formData,
                        type: "POST",
                        processData: false, // 告诉jQuery不要去处理发送的数据
                        contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                        beforeSend: function () {
                            // 上传前的回调，可以在这里做一些准备工作，比如显示加载动画
                            layer.load();
                        },
                        success: function (res) {
                            // 关闭加载动画
                            layer.closeAll('loading');
                            // 如果上传成功，这里res是后端返回的数据
                            if (res.code === 0) {
                                layer.msg('文件上传成功！');
                                //刷新页面
                                location.reload();

                                // 这里可以添加其他逻辑，比如刷新页面或显示上传的文件信息
                            } else {
                                layer.msg('文件上传失败：' + res.msg);
                                // 可以添加错误处理逻辑，比如重试上传或显示更详细的错误信息
                            }
                        },
                        error: function () {
                            // 关闭加载动画
                            layer.closeAll('loading');
                            // 请求异常回调
                            layer.msg('文件上传出错');
                            // 可以添加异常处理逻辑，比如提示用户检查网络连接或文件是否损坏
                        }
                    });
                }
            });


            // 搜索提交
            form.on('submit(demo-table-search)', function (data) {
                var field = data.field; // 获得表单字段
                // 执行搜索重载
                ShowWorkCenter(pageIndex, pageSize, $("#workCenterState").val());

                return false; // 阻止默认 form 跳转
            });

            let totalcou = 1;
            let pagecou = 10;

            //工作中心列表
            function ShowWorkCenter(val, sass, state) {
                var table = document.querySelector("table.layui-table tbody");
                let data = {
                    workCenterCode: $("#workCenterCode").val(),
                    workCenterName: $("#workCenterName").val(),
                    workCenterType: $("#workCenterType").val(),
                    workCenterState: state,
                    pageIndex: val,
                    pageSize: sass
                }
                console.log(data)
                $.ajax({
                    url: '@ViewBag.RedDragonWrite' + "/api/WorkCenter/QueryWorkCenter",
                    data: JSON.stringify(data),
                    type: "post",
                    dataType: "json",
                    contentType: "application/json",
                    success: res => {
                        var tbody = $("tbody");
                        tbody.empty(); // 清空tbody内容
                        if (res.data != null) {
                            totalcou = res.data.totalCount;
                            pagecou = res.data.pageCount;
                            $.each(res.data.list, function () {
                                tbody.append(`
                                                <tr>
                                                  <td>${this.workCenterId}</td>
                                                  <td>${this.workCenterCode}</td>
                                                  <td>${this.workCenterName}</td>
                                                  <td>${this.workCenterType}</td>
                                                  <td>${this.classes}</td>
                                                  <td>${this.createdOwner}</td>
                                                  <td>${new Date(this.createdTime).toLocaleDateString()}</td>
                                                  <td>${this.workCenterState == 1 ? '有效' : '无效'}</td>
                                                  <td>${this.approveState === 1 ? '未提交' : (this.approveState === 2 ? '已提交' : (this.approveState === 3 ? '已审批' : '已驳回'))} </td>
                                                  <td><button type="button" class="layui-btn layui-btn-xs" onclick="GetWorkCenter(${this.workCenterId})">编辑</button>
                                                  <button type="button" class="layui-btn layui-btn-xs" onclick="ExamWorkCenter()">审批</button>
                                                  <button type="button" class="layui-btn layui-btn-danger layui-btn-xs" onclick="DeleteWorkCenter(${this.workCenterId})">删除</button>
                                                 </td>
                                                 </tr>
                                                 `);
                            });
                        }

                        laypage.render({
                            elem: 'demo-laypage-all', // 使用正确的ID
                            curr: pageIndex, // 当前页
                            count: totalcou, // 数据总数
                            limit: pageSize, // 每页显示的条数
                            limits: [10, 15, 25], // 每页可以显示多少条
                            layout: ['count', 'prev', 'page', 'first', 'last', 'next', 'limit', 'skip'], // 自定义布局
                            jump: function (obj, first) {
                                if (!first) {
                                    pageIndex = obj.curr; // 更新当前页
                                    pageSize = obj.limit; // 更新每页显示的条数（如果需要的话）
                                    console.log(pageSize, pageIndex, "123123$$$");
                                    ShowWorkCenter(pageIndex, pageSize);
                                    form.render('table'); // 重新渲染下拉框
                                }
                                // 重新加载数据
                            }
                        });
                        console.log(996, pageSize, pageIndex, res);
                    }
                });
            }
        });

        //审批
        function ExamWorkCenter() {
            // 准备发送的数据
            const data = {
                workid: 1,
                username: "hhx", // 注意：这里的数据可能需要根据实际情况修改，例如使用实际的用户名
                userid: 1,   // 修正拼写错误，从 uSerid 到 userid
                workType: 1,
                gnumid: "hhx",
            };

            console.log(data);

            $.ajax({
                url: '@ViewBag.RedDragonWrite' + "/api/Inventory/ProcessFlowEngine",
                data: JSON.stringify(data),
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                success: function (res) {
                    console.log(res);
                    if (res.code === 1) {
                        let processStatusUpdate;
                        let message = res.msg;
                        if (message === "审批通过") {
                            processStatusUpdate = "审批中";
                        } else if (message === "撤销成功") {
                            processStatusUpdate = "开立";
                        }
                        // 更新状态（注意：这里仅做示例，实际状态更新可能需要在其他地方处理）
                        // let ProcessStatus = processStatusUpdate; // 如果需要在函数外使用，考虑将其定义为更高作用域的变量或返回
                        console.log("Process status updated to:", processStatusUpdate);
                        // 显示消息
                        layer.msg("审核通过");
                        // 刷新页面
                        // location.reload();
                    }
                }
            });
        }

        //导出
        function exportTableToExcel() {
            var table = document.querySelector("table.layui-table tbody");
            var ws = XLSX.utils.table_to_sheet(table);
            var wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
            XLSX.writeFile(wb, "工作中心列表.xlsx");
        }

        document.querySelector(".layui-btn.layui-bg-blue").addEventListener("click", exportTableToExcel);

        //删除工作中心
        function DeleteWorkCenter(workCenterId) {
            // 显示确认对话框
            if (confirm('您确定要删除这个工作中心吗？')) {
                var data = {
                    workCenterId: workCenterId
                };
                $.ajax({
                    url: '@ViewBag.RedDragonWrite' + "/api/WorkCenter/DeleteWorkCenter",
                    data: JSON.stringify(data),
                    type: "DELETE",
                    dataType: "json",
                    contentType: "application/json",
                    success: res => {
                        if (res.code == 0) {
                            layer.msg('删除成功');
                            location.reload();
                        } else {
                            layer.msg('删除失败');
                        }
                    }
                });
            } else {
                // 用户点击了取消按钮，不执行删除操作
                layer.msg('已取消删除');
            }
        }
    </script>
</body>
</html>


<script>

    //工作中心添加
    function AddWorkCenter() {
        location.href = "/WorkCenter/CreateWorkCenter"
    }

    //修改
    function GetWorkCenter(workCenterId) {
        localStorage.setItem("workCenterId", workCenterId)
        // location.href = '/WorkCenter/UpdateWorkCenter?workCenterId=' + workCenterId;
        location.href = '/WorkCenter/UpdateWorkCenter';
    }

</script>
